﻿using B.T.BasicData.Domain.RBAC;
using B.T.BasicData.ErrorCode;
using B.T.BasicData.Infraeturcture;
using B.T.BasicData.Read.Api.DTOs;
using B.T.BasicData.Read.Api.RBACServices.IServices;
using B.T.BasicData.Read.Api.RBACServices.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace B.T.BasicData.Read.Api.Controllers
{
    /// <summary>
    /// 权限管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class PermissionsController : ControllerBase
    {
        private readonly ILogger<PermissionsController> logger;
        private readonly IPermissionsServices _permissionsServices;

        public PermissionsController(ILogger<PermissionsController> logger, IPermissionsServices permissionsServices)
        {
            this.logger = logger;
            _permissionsServices = permissionsServices;
        }

        /// <summary>
        /// 获取当前登录用户的菜单树
        /// </summary>
        [HttpGet("user-menus")]
        public IActionResult GetUserMenus()
        {
            // 假设用户ID从Claims中获取（如JWT登录）
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
            if (userIdClaim == null)
            {
                return Unauthorized("无法获取用户ID");
            }
            if (!long.TryParse(userIdClaim.Value, out long userId))
            {
                return BadRequest("用户ID格式错误");
            }
            var menus = _permissionsServices.GetMenuTreeByUserId(userId);
            return Ok(menus);
        }


        /// <summary>
        /// 获取级联信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<ApiResult<List<TreeshapeDto>>> SearchTreeshape()
        {
            try
            {
                return await _permissionsServices.SearchTreeshape();
            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }
    }
}
